package com.william.jdbcplus.core.crud.impl;

import com.william.jdbcplus.common.entity.Entity;
import com.william.jdbcplus.core.crud.CrudConfig;
import com.william.jdbcplus.core.crud.IBaseCrud;
import com.william.jdbcplus.core.crud.IShardQuery;
import com.william.jdbcplus.core.enums.SqlMethod;
import com.william.jdbcplus.core.meta.TableHelperUtil;
import com.william.jdbcplus.core.meta.TableInfo;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 分片增删改查
 *
 * @author niliwei
 */
public class ShardCrud extends BaseCrud implements IShardQuery, IBaseCrud {

    private static ShardCrud instance = new ShardCrud();

    private ShardCrud() {
    }

    public static ShardCrud getInstance() {
        return instance;
    }

    @Override
    public <M extends Entity> Long queryMaxId(Class<M> entityClass, CrudConfig crudConfig) {
        SqlMethod sqlMethod = SqlMethod.SELECT_MAXID;
        TableInfo tableInfo = TableHelperUtil.getTableInfo(entityClass);
        String tableName = tableInfo.getTableName();
        String sql = String.format(sqlMethod.getSql(), tableInfo.getKeyColumn(), tableName);
        NamedParameterJdbcTemplate jdbcOpt = new NamedParameterJdbcTemplate(crudConfig.getJdbcTemplate());
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Long result = jdbcOpt.queryForObject(sql, paramMap, Long.class);

        if (result == null) {
            sql = String.format(sqlMethod.getSql(), tableInfo.getKeyColumn(), tableInfo.getTableName());
            result = jdbcOpt.queryForObject(sql, paramMap, Long.class);
        }

        return result;
    }

}
